#define _CRT_SECURE_NO_WARNINGS 1


#include<iostream>

using namespace std;

struct TreeNode {
    int val;
    TreeNode*left;
    TreeNode*right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode*left, TreeNode*right) : val(x), left(left), right(right) {}
 };
 
class Solution
{
public:
    TreeNode* insertIntoBST(TreeNode* root, int val)
    {
        if (root == nullptr)
        {
            root = new TreeNode(val);
            return root;
        }

        TreeNode* cur = root;
        TreeNode* parent = nullptr;
        while (cur)
        {
            if (val > cur->val)
            {
                parent = cur;
                cur = cur->right;
            }
            else if (val < cur->val)
            {
                parent = cur;
                cur = cur->left;
            }
            else
            {
                break;
            }
        }

        cur = new TreeNode(val);
        if (val > parent->val)
        {
            parent->left = cur;
        }
        else
        {
            parent->right = cur;
        }
        return root;
    }
};